<template>
    <div class="courseDetailsView">
        <div class="returnAndShareButton">
            <div class="returnButton button">
                <router-link to="/course" class="link">
                    <span class="iconfont icon-likesprograma-shangyibu1"></span>
                    返回
                </router-link>
            </div>
            <div class="shareButton button">
                <div class="link">
                    <span class="iconfont icon-likesprogramxiayibu"></span>
                    分享
                </div>
            </div>
        </div>
        <div class="courseInformation">
            <div class="courseName">
                {{ courseDetail?.courseInfo?.courseName }}
            </div>
            <div class="courseDescription">{{ courseDetail?.courseInfo?.courseDescription }}</div>
            <div class="courseTagsAndAddCourseButton">
                <span class="courseTagBox">
                    <div class="courseTags">
                        <span v-for="type in courseDetail?.courseType" :key="type.typeId" class="tag">{{ type.typeName }}</span>
                    </div>
                    <div class="courseTags">
                        <span v-for="label in courseDetail?.courseLabel" :key="label.labelId" class="tag">{{ label.labelName }}</span>
                    </div>
                </span>
                <span class="addCourseButton" @click="async () => {
                    if (permission > 0) {
                        router.push({ path: '/course/courseContent/' + courseId });
                    } else {
                        const success = await joinCourse();
                        if (success) router.push({ path: '/course/courseContent/' + courseId });
                    }
                }">
                    <span v-if="permission > 1">查看课程</span>
                    <span v-else-if="permission > 0">开始学习</span>
                    <span v-else>加入课程</span>
                </span>
            </div>
            <div class="courseDatas">
                <span class="courseData courseNumberOfLearners">
                    {{ courseDetail?.courseFigures?.studentCount }} 人学过
                </span>
                <span class="courseData courseNumberOfEvaluations">
                    {{ courseDetail?.courseFigures?.commentCount }} 次评价
                </span>
                <span class="courseData courseDifficulty">
                    难度：{{ courseDetail?.courseDifficulty?.difficultyName }}
                </span>
                <span class="courseData courseScore">
                    综合评分：
                    <ScoreComponent v-if="courseDetail?.courseFigures" v-model="courseDetail.courseFigures.avgScore" :showText="true"></ScoreComponent>
                </span>
                <span class="courseData courseDataEnd courseUpdateTime">
                    {{ courseDetail?.courseFigures?.updateTime }} 更新
                </span>
            </div>
        </div>
        <div class="courseDetailsContent">
            <div class="navigation">
                <router-link class="link" :to="'/course/courseDetails/' + courseId">
                    课程介绍
                </router-link>
                <router-link class="link" :to="'/course/courseDetails/' + courseId + '/courseChapterList'">
                    章节目录
                </router-link>
                <router-link class="link" :to="'/course/courseDetails/' + courseId + '/courseResources'">
                    课程资源
                </router-link>
                <router-link class="link" :to="'/course/courseDetails/' + courseId + '/courseEvaluate'">
                    课程评价
                </router-link>
            </div>
            <div class="courseDetailsContentView">
                <router-view v-slot="{ Component }">
                    <component 
                        :is="Component"
                        :pCourseTeacher="courseDetail?.courseTeacher"
                        :pRecommendCourse="courseDetail?.recommendCourse"
                        :pPermission="permission"
                        :joinCourse="joinCourse"
                    />
                </router-view>
            </div>
        </div>
        <!-- 消息对话框 -->
        <MessageDialog ref="messageDialog">
            <template v-slot:title>
                <span>{{ messageDialogData.title }}</span>
            </template>
            <template v-slot:content>
                <div class="dialogContent">
                    <div class="messageBox" :class="messageDialogData.type">
                        <div class="message" v-for=" message in messageDialogData.message">{{ message }}</div>
                    </div>
                </div>
            </template>
            <template v-slot:footer>
                <div class="dialogFooterButton" @click="closeMessage()">
                    <span class="line">取消</span>
                </div>
                <div class="dialogFooterButton" @click="closeMessage(true)">
                    <span>确认</span>
                </div>
            </template>
        </MessageDialog>
    </div>
</template>

<script lang="ts">
import { inject, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router'
import { courseApi } from '@/api/course/Course';
import MessageDialog from '@/components/MessageDialog.vue';
import { CourseDetail } from '@/types/Course';
import { userApi } from '@/api/Users';
import ScoreComponent from '@/components/ScoreComponent.vue';

export default {
  name: 'courseDetailsView'
};
</script>

<script setup lang="ts">
    const router = useRouter();     // 路由对象
    const route = useRoute();  // 获取路由参数
    const courseId = ref<number>(0); // 初始化为 null
    
    // 课程信息
    const courseDetail = ref<CourseDetail>(null);
    
    const permission = ref(0);

    const updateCourseId = (newCourseId: string | number | undefined | null) => {
        if (!newCourseId) return;
        
        const parsedCourseId = parseInt(newCourseId as unknown as string, 10);
        if (isNaN(parsedCourseId)) return;
        courseId.value = parsedCourseId;
        courseApi.getMemberPermission(courseId.value).then(res => {
            permission.value = res;
        });
        courseApi.findCourseInfo(courseId.value, 1).then(res => {
            courseDetail.value = res;
        });
    };

    // 确保 params.courseId 存在并且是一个有效的数字
    watch(() => route.params.courseId, (newId) => {
        console.log('路由参数更新了', newId);
        updateCourseId(newId as unknown as string);
    }, {
      immediate: true
    });

    // 处理同一组件内的参数更新
    onBeforeRouteUpdate((to) => {
        console.log('路由更新了', to);
        updateCourseId(to.params.courseId as unknown as string);
    });
    
    // 注入父组件提供的函数 接收搜索事件
    const takeOverSearch = inject<(
        search: (input: string) => void, prompt: (input: string) => Array<Object>, placeholder: string | undefined
    ) => void>("takeOverSearch");

    // 注入父组件提供的函数 释放搜索事件
    const releaseSearch = inject<() => void | undefined>("releaseSearch");

    // 页面加载，注入搜索事件
    onMounted(() => {
        takeOverSearch(null, null, "当前页面无法搜索");
    });

    // 离开页面时，释放搜索事件
    onUnmounted(() => {
        releaseSearch();
    });
    // 消息对话框
    const messageDialog = ref(null);
    const messageDialogData = ref({
        title: '',
        message: [''],
        type: 'success',
    });
    const showMessage = (title: string, message: string[], type: string) => {
        messageDialogData.value = {title, message, type};
        messageDialog.value.ShowModal();
    }
    const closeMessage = async (confirm?:boolean) => {
        messageDialog.value.Close();
        if (confirm === true && await userApi.isTokenExpired().then(res => res).catch(() => true)) {
            router.push({ name: 'login'});
        }
    }

    // 加入课程
    const joinCourse = async (): Promise<boolean> => {
        if (permission.value > 1) {
            router.push("/course/courseContent/" + courseId.value);
            return true;
        } else {
            try {
                const userRes = await userApi.isTokenExpired().then(res => res).catch(() => true);
                if (userRes) {
                    showMessage("加入课程", ["请先登录，是否现在前往登录"], "success");
                    return false;
                }
                const res = await courseApi.joinCourse(courseId.value);
                if (res.code === 200) {
                    showMessage("加入课程", [res.message], "success");
                    permission.value = 1;
                    return true;
                }
                showMessage("加入课程", [res.message], "failure");
                return false;
            } catch (error) {
                showMessage("加入课程", ["加入课程失败"], "failure");
                return false;
            }
        }
    };
</script>


<style src="@/assets/icons/iconfont.css" scoped></style>

<style scoped>
.courseDetailsView {
    width: var(--width);
    height: 100%;
    position: relative;
}

/* 顶部- 两个按钮 */
.courseDetailsView .returnAndShareButton {
    width: 100%;
    height: 40px;
    margin: 30px 0px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.courseDetailsView .returnAndShareButton .button .link {
    display: flex;
    justify-content: center;
    align-items: center;
}

.courseDetailsView .returnAndShareButton .link {
    transition: all 0.3s;
}

.courseDetailsView .returnAndShareButton .returnButton .link {
    color: rgba(0, 0, 0, 1);
}

.courseDetailsView .returnAndShareButton .link:hover {
    color: rgba(65, 185, 255, 1);
}

.courseDetailsView .returnAndShareButton .link .iconfont {
    margin-right: 5px;
    font-size: 24px;
}

.courseDetailsView .returnAndShareButton .shareButton {
    padding: 0px 8px;
    border-radius: 20px;
    background-color: rgba(100, 100, 100, .5);
    color: rgba(255, 255, 255, 1);
    transition: all 0.3s;
}

.courseDetailsView .returnAndShareButton .shareButton:hover {
    background-color: rgba(255, 255, 255, 1);
}

/* 课程信息 */
.courseDetailsView .courseInformation {
    width: 100%;
}

.courseDetailsView .courseInformation .courseName {
    font-size: 38px;
    font-weight: bold;
}

.courseDetailsView .courseInformation .courseDescription {
    width: 100%;
    color: rgba(100, 100, 100, 1);
}

.courseDetailsView .courseInformation .courseTagsAndAddCourseButton {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.courseDetailsView .courseInformation .courseTagBox {
    width: calc(100% - 200px);
    height: 100px;
    display: inline-block;
    padding: 10px 0px;
}
.courseDetailsView .courseInformation .courseTagBox .courseTags {
    display: flex;
    justify-self: flex-start;
    align-items: flex-start;
}

.courseDetailsView .courseInformation  .courseTagBox .courseTags .tag {
    padding: 5px 10px;
    margin-right: 10px;
    margin-bottom: 10px;
    background-color: rgba(65, 185, 255, 1);
    border-radius: 5px;
    color: rgba(255, 255, 255, 1);
}

.courseDetailsView .courseInformation .addCourseButton {
    padding: 20px 35px;
    border-radius: 10px;
    color: rgba(255, 255, 255, 1);
    transition: all 0.3s;
    font-weight: bold;
    font-size: 24px;
    background-color: rgba(65, 185, 255, 1);
}

.courseDetailsView .courseInformation .addCourseButton:hover {
    font-size: 28px;
}

.courseDetailsView .courseInformation .addCourseButton:active {
    transition: all 0.1s;
    font-size: 24px;
}

.courseDetailsView .courseInformation .courseDatas {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.courseDetailsView .courseInformation .courseDatas .courseData {
    padding: 0 10px;
    border-right: 1px solid rgba(0, 0, 0, .4);
}
.courseDetailsView .courseInformation .courseDatas .courseDataEnd {
    border-right: 0px;
}
.courseDetailsView .courseInformation .courseDatas .courseData.courseScore {
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.courseDetailsView .courseDetailsContent {
    width: 100%;
    padding: 20px 0px;
    position: relative;
}

.courseDetailsView .courseDetailsContent .navigation {
    width: 100%;
    padding-bottom: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.courseDetailsView .courseDetailsContent .navigation .link {
    transition: all 0.3s;
    padding: 3px 3px;
    margin: 0px 15px;
    font-size: 20px;
    color: rgba(0, 0, 0, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
}

.courseDetailsView .courseDetailsContent .navigation .link::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 50%;
    transform: translateX(-50%);
    width: 0%;
    height: 2px;
    transition: .3s all;
    background-color: rgba(65, 185, 255, 1); 
}

.courseDetailsView .courseDetailsContent .navigation .link:hover {
    color: rgba(65, 185, 255, 1);
}.courseDetailsView .courseDetailsContent .navigation .link:hover::after {
    width: 55%;
}

.courseDetailsView .courseDetailsContent .navigation .router-link-exact-active {
    color: rgba(65, 185, 255, 1);
}.courseDetailsView .courseDetailsContent .navigation .router-link-exact-active::after {
    width: 55%;
}


.courseDetailsView .courseDetailsContent .courseDetailsContentView {
    width: 100%;
    height: calc(100% - 80px);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 2rem;
    position: relative;
    background-color: rgba(255, 255, 255, .5);
    	backdrop-filter: blur(2rem);
    	-webkit-backdrop-filter: blur(2rem);
    	-moz-backdrop-filter: blur(2rem);
    	-ms-backdrop-filter: blur(2rem);
}


/* 对话框底部按钮 */
.dialogFooterButton {
    width: 100%;
    height: 65px;
    position: relative;
    display: flex;
    color: rgba(65, 185, 255, 1);
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: .3s all;
}
.dialogFooterButton:hover {
    background-color: rgba(200, 200, 200, .15);
}
.dialogFooterButton:active {
    transition: .1s all;
    background-color: rgba(220, 220, 220, .1);
}
.dialogFooterButton .line {
    width: 100%;
    border-right: 1px solid rgba(200, 200, 200, 1);
    display: flex;
    justify-content: center;
    align-items: center;
}
.messageBox {
    padding: 10px;
}
.messageBox.success {
    color: rgba(65, 185, 255, 1);
}
.messageBox.failure {
    color: rgba(255, 0, 0, 1);
}
</style>
